﻿/**
 * GoText Palm: A program that allows to send text messages over the internet.
 *  Copyright (C) 2008 Nicola 'Gawaine' Racco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using GoTextPalm.Core;
using GoTextPalm.Core.Data;
using GoTextPalm.Core.Persistence;
using GoTextPalm.Core.Localization;

namespace GoTextPalm.Gui
{
    public partial class ServicesForm : LocalizedForm
    {
        private Boolean modified = false;
        private Logic logic;

        public ServicesForm()
        {
            logic = new Logic();
            logic.ErrorCausedEvent += new Logic.ErrorCausedHandler(Logic_ErrorCaused);
            logic.LoadedDataEvent += new Logic.LoadedDataHandler(Logic_LoadedData);
            logic.StatusTextChangedEvent += new Logic.StatusTextChangedHandler(Logic_StatusTextChanged);

            InitializeComponent();
            header.Text = "Services";
            AddMenusToDictionary();
            UpdateResources();
        }

        protected override void AddMenusToDictionary() {
            AddMenuToDictionary(mnuNew, "mnuNew");
            AddMenuToDictionary(mnuDel, "mnuDel");
            AddMenuToDictionary(mnuConfig, "mnuConfig");
            AddMenuToDictionary(mnuNewScratch, "mnuNewScratch");
            AddMenuToDictionary(mnuNewRep, "mnuNewRep");
        }

        private void mnuNewScratch_Click(object sender, EventArgs e)
        {
            if (new NewServiceForm().ShowDialog() == DialogResult.OK)
            {
                modified = true;
                srvLst.Items.Clear();
                srvLst.Enabled = mnuNew.Enabled = false;
                new Thread(new ThreadStart(logic.LoadProcedure)).Start();
            }
        }

        
        private void mnuNewRep_Click(object sender, EventArgs e)
        {
            if (new FromRepositoryForm().ShowDialog() == DialogResult.OK)
            {
                modified = true;
                srvLst.Items.Clear();
                srvLst.Enabled = mnuNew.Enabled = false;
                new Thread(new ThreadStart(logic.LoadProcedure)).Start();
            }
        }

        private void srvLst_ItemActivate(object sender, EventArgs e)
        {
            if (new ConfigServiceForm(
                (Service)srvLst.Items[srvLst.SelectedIndices[0]].Tag
                ).ShowDialog() == DialogResult.OK)
            {
                modified = true;
                srvLst.Items.Clear();
                srvLst.Enabled = mnuNew.Enabled = false;
                new Thread(new ThreadStart(logic.LoadProcedure)).Start();
            }
        }

        private void mnuConfig_Click(object sender, EventArgs e)
        {
            srvLst_ItemActivate(sender, e);
        }

        private void mnuDel_Click(object sender, EventArgs e)
        {
            Service s = (Service)srvLst.Items[srvLst.SelectedIndices[0]].Tag;
            if (MessageBox.Show(String.Format(
                Utility.Tr("ServicesForm_delsrv", 
                "Do you want to remove the service '{0}' ?"), s.Name), header.Text,
                MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {
                logic.Selected = s;
                srvLst.Enabled = mnuNew.Enabled = false;
                new Thread(new ThreadStart(logic.DeleteService)).Start();
            }
        }

        private void srvLst_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (srvLst.SelectedIndices.Count == 0)
                srvLst.ContextMenu = null;
            else
                srvLst.ContextMenu = ctxMenu;
        }

        private void ServicesForm_Load(object sender, EventArgs e)
        {
            if (customInputPanel.SipSupported)
            {
                customInputPanel.Screen = screen;
                customInputPanel.Refresh();
            }
            srvLst.Items.Clear();
            srvLst.Enabled = mnuNew.Enabled = false;
            new Thread(new ThreadStart(logic.LoadProcedure)).Start();
        }

        private void ServicesForm_Closing(object sender, CancelEventArgs e)
        {
            if (modified)
                DialogResult = DialogResult.OK;
        }


        public void Logic_LoadedData(List<Service> sl)
        {
            if (InvokeRequired)
            {
                Logic.LoadedDataHandler func = Logic_LoadedData;
                Invoke(func, sl);
                return;
            }
            stsBar.Visible = stsBar.ProgressStarted = false;
            srvLst.Enabled = mnuNew.Enabled = true;

            srvLst.Items.Clear();
            foreach (Service s in sl)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Text = s.Name;
                lvi.Tag = s;
                lvi.ImageIndex = s.Config != null ? 0 : 1;
                srvLst.Items.Add(lvi);
            }
            srvLst.Refresh();
        }

        public void Logic_StatusTextChanged(String text)
        {
            if (InvokeRequired)
            {
                Logic.StatusTextChangedHandler func = Logic_StatusTextChanged;
                Invoke(func, text);
                return;
            }
            if (!stsBar.Visible)
                stsBar.Visible = stsBar.ProgressStarted = true;
            stsBar.Text = text;
        }

        public void Logic_ErrorCaused(String text)
        {
            if (InvokeRequired)
            {
                Logic.ErrorCausedHandler func = Logic_ErrorCaused;
                Invoke(func, text);
                return;
            }
            stsBar.Visible = stsBar.ProgressStarted = false;
            srvLst.Enabled = mnuNew.Enabled = true;
            MessageBox.Show(text, header.Text, MessageBoxButtons.OK, 
                MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
        }

        private class Logic
        {
            public delegate void StatusTextChangedHandler(String text);
            public event StatusTextChangedHandler StatusTextChangedEvent;

            public delegate void ErrorCausedHandler(String text);
            public event ErrorCausedHandler ErrorCausedEvent;

            public delegate void LoadedDataHandler(List<Service> lvis);
            public event LoadedDataHandler LoadedDataEvent;

            public Service Selected;

            public void LoadProcedure()
            {
                try
                {
                    FireStatusTextChanged(Utility.Tr("ServicesForm_sts3", "Loading Services ..."));
                    Service[] sl = DBService.GetServices();
                    FireLoadedData(new List<Service>(sl));
                }
                catch (Exception ex)
                {
                    FireErrorCaused(String.Format(
                        Utility.Tr("ServicesForm_cantload", 
                        "Cannot load Services: {0}"), ex.Message));
                }
            }

            public void DeleteService()
            {
                FireStatusTextChanged(Utility.Tr("ServicesForm_sts2", "Removing Service ..."));
                try
                {
                    ServiceLogic.DeleteService(Selected);
                    LoadProcedure();
                }
                catch (Exception e)
                {
                    FireErrorCaused(String.Format(
                        Utility.Tr("ServicesForm_cantdel", 
                        "Cannot remove the service: {0}"), e.Message));
                }
            }

            private void FireLoadedData(List<Service> sl)
            {
                if (LoadedDataEvent != null)
                    LoadedDataEvent(sl);
            }

            private void FireErrorCaused(String text)
            {
                if (ErrorCausedEvent != null)
                    ErrorCausedEvent(text);
            }

            private void FireStatusTextChanged(String text)
            {
                if (StatusTextChangedEvent != null)
                    StatusTextChangedEvent(text);
            }
        }
    }
}